package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.*;
import com.cskaoyan.shopping.constants.GlobalConstants;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.converter.ProductConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.ItemMapper;
import com.cskaoyan.shopping.dal.persistence.PanelContentMapper;
import com.cskaoyan.shopping.dal.persistence.PanelMapper;
import com.cskaoyan.shopping.dto.*;
import com.cskaoyan.shopping.service.IProductService;
import com.cskaoyan.user.constants.UserRetCode;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RMap;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 商品接口
 *
 * @author D_y_Y
 * @since 2022/06/18 14:01
 */
@Slf4j
@Service
public class IProductServiceImpl implements IProductService {
    @Autowired
    ItemMapper itemMapper;
    @Autowired
    PanelMapper panelMapper;

    @Autowired
    PanelContentMapper panelContentMapper;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    ContentConverter contentConverter;

    @Autowired
    RedissonClient redissonClient;

    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();
        try {
            request.requestCheck();
            Item items = itemMapper.selectItem(request.getId());
            String desc = itemMapper.selectDescById(request.getId());

            ProductDetailDto productDetailDto = productConverter.item2ProductDetail(items);
            productDetailDto.setDetail(desc);
            productDetailResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
            productDetailResponse.setProductDetailDto(productDetailDto);

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(productDetailResponse, e);
        }
        return productDetailResponse;
    }

    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        //设置日志
        log.error("IProductServiceImpl.getAllProduct request :" + request);
        request.requestCheck();
        if (request.getPriceGt() == null) {
            request.setPriceGt((Integer) 0);
        }
        if (request.getPriceLte() == null) {
            request.setPriceLte(999999999);
        }
        RMap<String, List<Item>> map = redissonClient.getMap(GlobalConstants.SHOPPING_ALL_GOODS);
        if (map.size() == 0) {
            AllProductResponse allProductResponse = new AllProductResponse();

            //开启分页
            PageHelper.startPage(request.getPage(), request.getSize());
            //查询所有商品
            Example example = new Example(Item.class);
            example.createCriteria().andBetween("price", request.getPriceGt(), request.getPriceLte());
            List<Item> items = itemMapper.selectByExample(example);
            PageInfo pageInfo = new PageInfo(items);
            long total = pageInfo.getTotal();
            //放入redis
            map.put("allgoods", itemMapper.selectAll());

            //List<Item> itemList = items.stream().filter(a -> request.getPriceGt()<a.getPrice().intValue()&&a.getPrice().intValue() <  request.getPriceLte()).collect(Collectors.toList());

            //converter转换
            List<ProductDto> productDtos = productConverter.items2Dto(items);
            //

            allProductResponse.setTotal(total);
            allProductResponse.setData(productDtos);
            allProductResponse.setCode("000000");
            allProductResponse.setMsg("成功");
            log.info("IProductServiceImpl.getAllProduct query :" + allProductResponse);

            return allProductResponse;

        } else {
            List<Item> items = map.get("allgoods");
            AllProductResponse allProductResponse = new AllProductResponse();
            List<Item> itemList = items.stream()
                    .filter(a -> request.getPriceGt() < a.getPrice().intValue() && a.getPrice().intValue() < request.getPriceLte())
                    .skip((request.getPage()-1)*request.getSize())
                    .limit(request.getSize())
                    .collect(Collectors.toList());
            Long total = items.stream().filter(a -> request.getPriceGt() < a.getPrice().intValue() && a.getPrice().intValue() < request.getPriceLte()).count();
            List<ProductDto> productDtoList = productConverter.items2Dto(itemList);
            allProductResponse.setProductDtoList(productDtoList);
            allProductResponse.setData(productDtoList);
            allProductResponse.setTotal(total);
            allProductResponse.setMsg(UserRetCode.SUCCESS.getMessage());
            allProductResponse.setCode(UserRetCode.SUCCESS.getCode());
            return  allProductResponse;

        }


    }

    @Override
    public RecommendResponse getRecommendGoods() {
        //设置日志
        log.error("IProductServiceImpl.getRecommendGoods");
        RecommendResponse response = new RecommendResponse();
        Example example = new Example(Panel.class);
        // example.createCriteria().andEqualTo("id",GlobalConstants.RECOMMEND_PANEL_ID);
        // List<Panel> panels = panelMapper.selectByExample(example);
        List<Panel> panels = panelMapper.selectPanelContentById(GlobalConstants.RECOMMEND_PANEL_ID);

        LinkedHashSet<PanelDto> panelDtos = new LinkedHashSet<>();


        for (Panel panel : panels) {
            List<PanelContentItem> panelContentItems = panelContentMapper.selectPanelContentAndProductWithPanelId(panel.getId());
            List<PanelContentItemDto> panelContentItemDtos = contentConverter.panelContentItem2Dto(panelContentItems);
            PanelDto panelDto = contentConverter.panel2Dto(panel);
            panelDto.setPanelContentItems(panelContentItemDtos);
            panelDtos.add(panelDto);

        }

        response.setPanelContentItemDtos(panelDtos);
        log.info("IProductServiceImpl.getRecommendGoods query :" + response);
        response.setCode("000000");
        response.setMsg("成功");
        return response;

    }

    @Override
    public AllItemResponse getAllItems() {
        return null;
    }
}
